using PKGames.Localization;
using System;
using UnityEngine;

namespace PKGames
{
	public abstract class AbstractWindow : MonoBehaviour
	{
		private GameObject _windowHolder;

		private Action<AbstractWindow, bool> _closeWindow;

		private Action<GameObject> _destroyWindow;

		[Header("Transition Settings")]
		[SerializeField]
		private WindowTransition _windowTransition;

		[SerializeField]
		private WindowTransition _rotationTransition;

		[Header("Orientation Settings")]
		[SerializeField]
		private bool _isPortrait;

		[Header("Translation Settings")]
		[SerializeField]
		private LocalizedField[] _textsToTranslate;

		protected LocationProvider _locationProvider;

		public GameObject WindowHolder => _windowHolder;

		public WindowTransition WindowTransition => _windowTransition;

		public WindowTransition RotationTransition => _rotationTransition;

		public bool IsPortrait => _isPortrait;

		protected virtual void Awake()
		{
			_locationProvider = MonoSingleton<LocationProvider>.Instance;
		}

		protected virtual void OnDestroy()
		{
			_locationProvider = null;
		}

		public virtual void SetupWindow(GameObject windowHolder, Action<AbstractWindow, bool> closeWindow, Action<GameObject> destroyWindow, params object[] args)
		{
			_closeWindow = closeWindow;
			_destroyWindow = destroyWindow;
			_windowHolder = windowHolder;
			UpdateLocalizedFields();
		}

		public void CloseWindow()
		{
			CloseWindow(ignoreTransition: false);
		}

		public virtual void CloseWindow(bool ignoreTransition)
		{
			if (_closeWindow != null)
			{
				_closeWindow(this, ignoreTransition);
			}
		}

		public void DestroyWindow()
		{
			if (_destroyWindow != null)
			{
				_destroyWindow(_windowHolder);
			}
		}

		public CanvasGroup WindowCanvasGroup()
		{
			return _windowHolder.GetComponent<CanvasGroup>();
		}

		public virtual void LanguageChanged()
		{
			UpdateLocalizedFields();
		}

		private void UpdateLocalizedFields()
		{
			LocalizedField[] textsToTranslate = _textsToTranslate;
			foreach (LocalizedField localizedField in textsToTranslate)
			{
				localizedField.UpdateLocalizedText(_locationProvider);
			}
		}
	}
}
